package com.xin.uploadanddownload.service.impl;

import com.xin.uploadanddownload.model.FileVo;
import com.xin.uploadanddownload.service.FileService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    private String  basePath ="D:/";
    @Override
    public FileVo upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String prefix = UUID.randomUUID().toString().replace("-","");
        String fileType = originalFilename.substring(originalFilename.indexOf("."));
        String storageFileName=prefix+fileType;
        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        String realPath=basePath+datePath;
        File dirPath = new File(realPath);
        if (!dirPath.exists()){
            dirPath.mkdirs();
        }
        String absolutePath=realPath+storageFileName;
        System.out.println(absolutePath);
        file.transferTo(new File(absolutePath));
        return null;
    }
    @Override
    public Object download(OutputStream os, String filePath) throws IOException {
        //下载文件的路径
        String downPath = basePath+filePath;
        //读取目标文件
        File f = new File(downPath);
        //创建输入流
        InputStream is = new FileInputStream(f);
        //做一些业务判断，我这里简单点直接输出，你也可以封装到实体类返回具体信息
        if (is == null) {
            System.out.println("文件不存在");
        }
        //利用IOUtils将输入流的内容 复制到输出流
        //org.apache.tomcat.util.http.fileupload.IOUtils
        //项目搭建是自动集成了这个类 直接使用即可
        IOUtils.copy(is, os);
        os.flush();
        is.close();
        os.close();
        return null;
    }

}
